<style type="text/css" title="currentStyle">
	@import "../media/css/demo_table.css";
	@import "media/css/TableTools.css";
</style>

<script type="text/javascript" charset="utf-8" src="../media/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf-8" src="media/ZeroClipboard/ZeroClipboard.js"></script>
<script type="text/javascript" charset="utf-8" src="media/js/TableTools.js"></script>
<script type="text/javascript" charset="utf-8">
	$(document).ready( function () {
		$('#tableContact').dataTable();
	} );
</script>
<?php
if(isset($_POST[txtDelContId]) && $_POST[txtDelContId]!="")
{
	//$data['di_assignedDriverId'] = 0;
	//if($db->query_update("tb_deviceinfo", $data , "di_id=".$deviceAllId[$i]))	
	$sql = "DELETE FROM tb_client_driver_info WHERE tcdi_id =".$_POST[txtDelContId];
	$rows = $db->query($sql);
}
if(isset($_POST[txtContId]) && $_POST[txtContId] !='' && $_POST[txtDeviceId] == '' && $_POST[txtAllDeviceId] =='')
{
	$sql = "SELECT * FROM tb_client_driver_info WHERE tcdi_id =".$_POST[txtContId];
	$rows = $db->query($sql);
	if($db->affected_rows > 0)
	{
		$deviceRecord = $db->fetch_array($rows);
	}
}
if(isset($_POST[txtContId]) && $_POST[txtContId] !='' && $_POST[txtDeviceId] == '' && $_POST[txtAllDeviceId]!='')
{
	//exit;
	header("location:?ch=status&au=24&msg=0");
	exit;
}
if(isset($_POST[txtContId]) && $_POST[txtContId] !='' && $_POST[txtDeviceId] != '' && $_POST[txtAllDeviceId]!='')
{
	$deviceAllId = explode(",",$_POST[txtAllDeviceId]);
	
	for($i=0;$i<count($deviceAllId)-1;$i++)
	{
		//echo "<br>".$_POST[txtDeviceId]."=".$deviceAllId[$i];
		if($_POST[txtDeviceId] == $deviceAllId[$i])
		{
			$data['di_assignedDriverId'] = $_POST[txtContId];	
		}
		else
		{
			$data['di_assignedDriverId'] = 0;
		}
		$db->query_update("tb_deviceinfo", $data , "di_id=".$deviceAllId[$i]);
	}
	
	header("location:?ch=status&au=26&msg=1");
	exit;
	
}

?>
<script type="text/javascript" language="javascript">
function mobileNoValid(id)
{
	objMobileNo = document.getElementById(id);
	if(document.getElementById(id).value.length != 10 || document.getElementById(id).value.search(/[^0-9\-()+]/g) != -1 )
	{
		//alert('Please enter valid 10 digit mobile number');
		//objMobileNo.focus();
		//objMobileNo.value="";
		return false;
	}
	else
	return true; 
	
}
var ajax1=new sack();

function validContForm()
{
var f = 0;
	/*	
	if(document.getElementById('txtContName').value == "" )
	{
		alert("Enter Name"); 
		document.getElementById('txtContName').focus();
		f = 1;
		return false;
	}
	else f =0;*/

	if(f == 0)
	{
		return true;
	}else return false;
	
}
function validTable()
{
	var t = 0;
	var h = 0;
	var tmp = '';
	while(h<3)
	{
		if(document.getElementById('sdHeader'+h).value == '')
		{
			alert("Choose Header in row "+(h+1)); 
			document.getElementById('sdHeader'+h).focus();
			t = 1;
			return false;
		}
		else 
		{
			if(tmp.search(document.getElementById('sdHeader'+h).value) == -1)
			{
				tmp +=document.getElementById('sdHeader'+h).value+",";
				t = 0;	
				h++;
			}
			else
			{
				alert("Choose Different Header in row "+(h+1)); 
				document.getElementById('sdHeader'+h).focus();
				t = 1;
				return false;
			}
		}
	}
	if(t == 0) document.frmCSVdata.submit();

}
function funEditUser(drid,did,aid,act)
{
	document.frmSubmit.txtContId.value = drid;
	document.frmSubmit.txtDeviceId.value = did;
	document.frmSubmit.txtAllDeviceId.value = aid;
	document.frmSubmit.action = act;
	document.frmSubmit.submit();
}
function readDetails(val)
{
	if(validTable)
	{
		if(document.getElementById('sdHeader'+h).value == '')
		{
			alert("Choose Header in row "+(h+1)); 
			document.getElementById('sdHeader'+h).focus();
			t = 1;
			return false;
		}
	}
}
function deleteUser(did,act)
{
  if (confirm("Are you sure you want to delete")) 
  {
	document.frmDelSubmit.txtDelContId.value = did;
	document.frmDelSubmit.action = act;
	document.frmDelSubmit.submit();
  }
}
function dispDeviceID(val)
{
	document.getElementById('selDeviceId').value = val;
}
function sendCSVData()
{
//alert(c1);
document.frmTripData.submit();
//	window.location.href='export.php?csvData='+c1+'&frdate='+c2+'&frtime='+c3+'&totime='+c4+'&vehino='+c5;
	//document.write('export.php?csvData='+c1+'&frdate='+c2+'&frtime='+c3+'&totime='+c4+'&vehino='+c5);
}
$(function() {
	$( "#txtDOB" ).datepicker({
		changeMonth: true,
		changeYear: true,
		minDate: 0,
		showOn: "button",
		buttonImage: "images/calendar.gif",
		buttonImageOnly: true,
		dateFormat : "dd-mm-yy"
	});
});
</script>
<form id="frmAddPolicy" name="frmAddPolicy" method="post" action="?ch=importPOI&step=2" enctype="multipart/form-data"> 
<input type="hidden" name="txtClientId" id="txtClientId" value="<?php echo $_SESSION[clientID];?>" />
<table class="gridform_final">
<tr><th colspan="2">Import POI</th></tr>
  <tr>
    <td width="20%" align="right">Import CSV file</td>
    <td width="30%" align="left">
        <input type="file" name="file_source" id="file_source" />
    </td>
  </tr>              
  <tr>
    <td style="text-align:right">
      <input type="submit" name="cmdImportCSV" id="cmdImportCSV" value="Upload" class="save_btn" tabindex="1" onclick="return validContForm();" />    
    </td>
    <td align="left">
      <input type="button" name="map_cancel_btn" id="map_cancel_btn" value="Reset" class="save_btn" onclick="location.href='index.php?ch=importPOI';" tabindex="2" /> 
    </td>
  </tr>  
</table>
</form>
<br />
<?php
if(isset($_POST[cmdImportCSV]) && $_POST[cmdImportCSV] && $_GET[step] == 2)
{
  $errorCode = $_FILES['file_source']['error'];
  if( 0 == $_FILES['file_source']['size'] )
  {
    $errorCode = -1; //empty file
  }
  
  $dataArray = array();
  if( is_uploaded_file($_FILES['file_source']['tmp_name']) && UPLOAD_ERR_OK == $errorCode )  //file was uploaded successfully
  {
    $temp_file = $_FILES['file_source']['tmp_name'];
    $our_file  = 'temp/csv/' . time().$_FILES['file_source']['name'];
    if ( !move_uploaded_file( $temp_file, $our_file ) ) //copy to our folder
    {
      $error = 'Could not copy [' . $temp_file .'] to [' . $our_file . ']';
    }
    else
    {
     	$_SESSION['our_file'] = $our_file;
      	header('location:?ch=importPOI&step=3');
    }
  }
  else //no, file was not uploaded, so let's rise an error
  {
 
    $error = coalesce( $uploadErrors[$errorCode], 'General upload error. Check <a href="http://php.net/manual/en/features.file-upload.php">file uploads settings</a> of your php.ini' );
    $_SESSION['data'] = array(); //erase previosly saved options
  }
}
else if($_GET[step] == 3)
{
	$fieldseparator = ",";
	$lineseparator = "\n";
	$csvfile = $_SESSION['our_file'];
	 
	 $file = fopen($csvfile,"r");

	if(!$file) {
		echo "Error opening data file.\n";
		exit;
	}
	
	$size = filesize($csvfile);
	
	if(!$size) {
		echo "File is empty.\n";
		exit;
	}
	
	$_SESSION[csvcontent] = fread($file,$size);
	fclose($file);
	
	$columnArr = array("Latitude","Longitude","Address");
	$lines = 0;
	$queries = "";
	$linearray = array();
	$csvData = explode($lineseparator,$_SESSION[csvcontent]);
	
	$header = explode(",",$csvData[0]);
	$sample = explode(",",$csvData[1]);
	?>
    <form name="frmCSVdata" id="frmCSVdata" method="post" action="?ch=importPOI&step=4">
    <table class="gridform_final" style="width:45%;" id="mappingTable">
    	<tr><th width="35%">Column Name</th><th>Header</th><th width="35%">Value</th>
    <?php
	for($i = 0; $i < count($columnArr); $i++)
	{
		$headSel = '<select name=sdHeader'.$i.' id=sdHeader'.$i.' style="width:100%">';
		$headSel .= '<option value="">Select Header</option>';
		for($k = 0; $k < count($header); $k++)
		{
			$headSel .= '<option value='.$k.'>'.$header[$k].'</option>';
		}
		$headSel .= '</select>';
		//echo "Name: $key, Age: $value <br />";
		echo "<tr><td>".$columnArr[$i]."</td><td>".$headSel."</td><td>".$sample[$i]."</td></tr>";
	}
	?>
    	<tr><td colspan="3" style="text-align:center">
        <input type="button" name="btnSubmitTable" id="btnSubmitTable" value="Import" class="save_btn" onclick="validTable()" tabindex="6" /> </td></tr>
    </table>
    <?php

}
else if($_GET[step] == 4 && $_SESSION[csvcontent]!="")
{
	$fieldseparator = ",";
	$lineseparator = "\n";
	//echo $_SESSION['our_file'];
	
	$tabColumnArr = array("tgi_latLong","tgi_name");
	$lines = 0;
	$queries = "";
	$linearray = array();
	$csvData = explode($lineseparator,$_SESSION[csvcontent]);
	//print_r($csvData);
	//exit;
	for($y = 1; $y < count($csvData)-1; $y++) 
	{
		$line = $csvData[$y];
		$line = trim($line," \t");
		$line = str_replace("\r","",$line);
		$line = str_replace("'","\'",$line);
		$linearray = explode($fieldseparator,$line);
		
		$linemysql = implode("','",$linearray);
		if($linearray[$_POST[sdHeader.$_POST[sdHeader0]]] != "" && $linearray[$_POST[sdHeader.$_POST[sdHeader1]]]!="" )
		{
			//$linemysql = "'".round($linearray[$_POST[sdHeader.$_POST[sdHeader0]]],6).",".round($linearray[$_POST[sdHeader.$_POST[sdHeader1]]],6)."','".$linearray[$_POST[sdHeader.$_POST[sdHeader2]]]."'";
			$data['tgi_isActive'] = 1;
			$data['tgi_radius'] = "0.50";
			$data['tgi_latLong'] = round($linearray[$_POST[sdHeader.$_POST[sdHeader0]]],6).",".round($linearray[$_POST[sdHeader.$_POST[sdHeader1]]],6);
			$data['tgi_name'] = $linearray[$_POST[sdHeader.$_POST[sdHeader2]]];
			$data['tgi_clientId'] = $_SESSION[clientID];
			//$queries .= $query . "\n";
			
			if($db->query_insert("tb_geofence_info", $data))
			$lines++;
		}
	}
	unlink($_SESSION['our_file']);
	unset($_SESSION['our_file']);
	unset($_SESSION['csvcontent']);
	header("location:?ch=status&au=27&msg=".$lines);
	exit;

}

